package com.menu.Configuration;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.unit.DataSize;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.MultipartConfigElement;

@Configuration
@Slf4j
public class UploadConfig implements WebMvcConfigurer {

    private static final String uploadFolder = System.getProperty("user.dir")+"/Static/";

    @Value("${server.port}")
    private int port;
    @Value("${server.servlet.context-path}")
    private  String path;
    @Value("${server.ip}")
    private  String ip;
    public static   String URL;
    @Value("${file.staticAccessPath}")
    private String accessPath;


    @Bean
    public MultipartConfigElement multipartConfigElement(){
        MultipartConfigFactory factory = new MultipartConfigFactory();
        factory.setLocation(uploadFolder);
        factory.setMaxFileSize(DataSize.ofMegabytes(100));
        factory.setMaxRequestSize(DataSize.ofMegabytes(1000));
        StringBuilder stringBuilder = new StringBuilder("http://");
        stringBuilder.append(ip);
        stringBuilder.append(":");
        stringBuilder.append(port);
        stringBuilder.append(path);
        URL = stringBuilder.toString();
        log.info(URL);
        return factory.createMultipartConfig();

    }

    /**
     * 配置访问资源和本地资源映射
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(accessPath).addResourceLocations("file:"+uploadFolder);
    }
}
